import { onBeforeMount, onMounted } from 'vue';

/**
 * 当窗口发生变化时
 * @param {function} callback 回调函数
 * @param {boolean} [immediate] 是否立即执行
 * @param {number} [delay] 延迟时间
 */
export default function useWindowResize(
  callback: () => void,
  immediate: boolean = true,
  delay: number = 200,
) {
  let timeId: NodeJS.Timeout;

  const handleOnResize = () => {
    clearTimeout(timeId);
    timeId = setTimeout(() => {
      callback();
    }, delay);
  };

  onMounted(() => {
    window.addEventListener('resize', handleOnResize);
    immediate && handleOnResize();
  });

  onBeforeMount(() => {
    window.removeEventListener('resize', handleOnResize);
  });
}
